package com.taylor.community.service;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.taylor.community.dao.CommentMapper;
import com.taylor.community.entity.Comment;
import com.taylor.community.util.CommunityConstant;
import com.taylor.community.util.SensitiveFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

@Service
public class CommentService implements CommunityConstant {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private SensitiveFilter sensitiveFilter;
    @Autowired
    private DiscussPostService discussPostService;
    @SentinelResource(value = "findCommentsByEntity")
    public List<Comment> findCommentsByEntity(int entityType,int entityId,int offset,int limit){
        return commentMapper.selectCommentsByEntity(entityType,entityId,offset,limit);
    }

    /**
     * 查找评论的数量
     * @param entityType
     * @param entityId
     * @return
     */
    public int findCommentCount(int entityType,int entityId){
        return commentMapper.selectCountByEntity(entityType,entityId);
    }

    /**
     * 添加评论（insert到comment表） + 更新帖子的评论数量（在discuss_post表）
     * 有两个表的操作，做事务管理
     *  @param comment
     * @return
     */
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
    public int addComment(Comment comment){
        if(comment == null){
            throw new IllegalArgumentException("参数不能为空！");
        }
        //添加评论 给评论做敏感词过滤
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
        comment.setContent(sensitiveFilter.filter(comment.getContent()));
        int rows = commentMapper.insertComment(comment);
        //更新帖子的数量 只有帖子类型才需要更新数量（discuss_post里有字段comment_count)
        if(comment.getEntityType() == ENTITY_TYPE_POST){
            //找到当前的帖子的评论数据量
            int count = commentMapper.selectCountByEntity(comment.getEntityType(),comment.getEntityId());
            discussPostService.updateCommentCount(comment.getEntityId(),count);
        }
        return rows;
    }

    /**
     * 查找用户对帖子的回复列表
     * @param userId
     * @param offset
     * @param limit
     * @return
     */
    public List<Comment> findUserComments(int userId,int offset,int limit){
        return commentMapper.selectCommentByUserId(userId,offset,limit);
    }

    /**
     * 查找用户对帖子回复的数量
     * @param userId
     * @return
     */
    public int findUserCount(int userId){
        return commentMapper.selectCountByUser(userId);
    }
    public Comment findCommentById(int userId){
        return commentMapper.selectCommentById(userId);
    }
}
